package com.poopinggames.juego1;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.v4.view.MotionEventCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;

public class GameView extends SurfaceView implements Callback {
	private static final int ROW=4;
	private static final int COL=4;
	
	private static final String TAG = "GAME VIEW";
	private int[] xSnap = new int[COL];
	private int[] ySnap = new int[ROW];
    List<Integer[]> posList= new ArrayList<Integer[]>();
	private int tol;
	private int mActivePointerId = MotionEvent.INVALID_POINTER_ID;
	private float xLast;
	private float yLast;
	private float mPosX;
	private float mPosY;
	private PiezaMovible pieza1;

	public GameView(Context context, AttributeSet attrs) {
		super(context, attrs);
		SurfaceHolder holder = getHolder();
		holder.addCallback(this);

	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		final int action = MotionEventCompat.getActionMasked(event);

		switch (action) {
		case MotionEvent.ACTION_DOWN: {

			final int pointerIndex = MotionEventCompat.getActionIndex(event);
			final float x = MotionEventCompat.getX(event, pointerIndex);
			final float y = MotionEventCompat.getY(event, pointerIndex);
			xLast = x;
			yLast = y;
			PiezaMovible.getActivePieza((int)x, (int)y);
			mActivePointerId = MotionEventCompat.getPointerId(event,
					pointerIndex);
			//Log.d(TAG, "ActionDown, pointerIndex = " + pointerIndex);
			break;
		}

		case MotionEvent.ACTION_MOVE: {
			final int pointerIndex = MotionEventCompat.findPointerIndex(event,
					mActivePointerId);
			final float x = MotionEventCompat.getX(event, pointerIndex);
			final float y = MotionEventCompat.getY(event, pointerIndex);
			final float dx = x - xLast;
			final float dy = y - yLast;
			SurfaceHolder holder = getHolder();
			Canvas canvas = holder.lockCanvas();
			final float width = canvas.getWidth();
			final float height = canvas.getHeight();
			holder.unlockCanvasAndPost(canvas);
			/*if (dx>0){
				pieza1.moveX(dx);
			}else {
				pieza1.moveX(dx);
			}
			if (dy>0){
				pieza1.moveBottom(dy);
			}else {
				pieza1.moveTop(-dy);
			}
			*/
			
			PiezaMovible.moveActivePieza((int)dx, (int)dy);
			
			//pieza1.moveMe(Math.round(dx), Math.round(dy));
			mPosX += dx;
			mPosY += dy;
			mPosX = mPosX < 0 ? 0 : mPosX;
			mPosY = mPosY < 0 ? 0 : mPosY;
			mPosX = mPosX > width ? width : mPosX;
			mPosY = mPosY > height ? height : mPosY;

			invalidate();
			// Log.d(TAG,"mPosX = " + mPosX);
			// Log.d(TAG,"mPosY = " + mPosY);

			xLast = x;
			yLast = y;
			break;
		}
		case MotionEvent.ACTION_CANCEL:
			mActivePointerId = MotionEvent.INVALID_POINTER_ID;
			PiezaMovible.deselectAll();
			break;
		case MotionEvent.ACTION_UP:
			mActivePointerId = MotionEvent.INVALID_POINTER_ID;
			PiezaMovible.snapAll(posList, tol);
			invalidate();
			PiezaMovible.deselectAll();
			break;
		case MotionEvent.ACTION_POINTER_UP: {
			final int pointerIndex = MotionEventCompat.getActionIndex(event);
			final int pointerId = MotionEventCompat.getPointerId(event,
					pointerIndex);

			if (pointerId == mActivePointerId) {
				// Log.d(TAG,"se solto el activePointer");
				//Log.d(TAG, "ActionPointerUp, pointerIndex = " + pointerIndex);
				final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
				xLast = MotionEventCompat.getX(event, newPointerIndex);
				yLast = MotionEventCompat.getY(event, newPointerIndex);
				mActivePointerId = MotionEventCompat.getPointerId(event,
						newPointerIndex);
			}
			break;
		}

		}

		return true;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		//Log.d(TAG, "onDraw");
		canvas.drawColor(Color.WHITE);
		Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
		paint.setTextSize(100);
		PiezaMovible.drawAll(canvas);
		//paint.setColor(Color.YELLOW);
		//paint.setStrokeWidth(5);
		//canvas.drawCircle(mPosX, mPosY, 50, paint);
		


	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {

		holder = getHolder();
		Canvas canvas = holder.lockCanvas();
		canvas.drawColor(Color.BLACK);
		int width = canvas.getWidth();
		int height = canvas.getHeight();

		int density = canvas.getDensity();
		Paint paint = new Paint();
		paint.setColor(Color.WHITE);
		paint.setStrokeWidth(10);
		
		
		if (height >= width) {
			height = width;
		} else {
			width = height;
		}
		
		int sizePieza = (width-100)/COL;
		tol=sizePieza/2;
		PiezaMovible.piezasList.clear();
		//Log.d(TAG,"antes las paredes");
		new PiezaMovible(0,25,height/2,50,height,false);
		new PiezaMovible(0,width - 25,height/2,50,height,false);
		new PiezaMovible(0,width/2,25,width-100,50,false);
		new PiezaMovible(0,width/2,height - 25,width-100,50,false);
		//Log.d(TAG,"cree las paredes");


        for (int r=0;r<ROW;r++){
            for (int c=0;c<COL;c++){
                Integer[] pos = new Integer[2];
                pos[0]=(int)(50+sizePieza/2 +c * sizePieza);
                pos[1]=(int)(50+sizePieza/2 +r * sizePieza);
                posList.add(pos);

            }
        }
        Set<Integer> initPos = new LinkedHashSet<Integer>();
        int k=0;
        Log.d(TAG,"initpos size = " + initPos.size());
        while (initPos.size()<COL*ROW){
            Random rnd = new Random();
            int number=rnd.nextInt(COL*ROW);
            initPos.add(number);
           // Log.d(TAG,"number = "+ number);
        }

        for (Integer value : initPos){

            int x=posList.get(value)[0];
            int y=posList.get(value)[1];
            if (k>0){
                new PiezaMovible(k,x,y,sizePieza,sizePieza,true);
            }
            k++;
        }
		/*for (int c=0;c<COL;c++){
			//Log.d(TAG,"voy por la c= " + c);
			
			xSnap[c]=(int)(50+sizePieza/2 +c * sizePieza);
			//Log.d(TAG,"agregue el primer xSnap");
			for (int r=0;r<ROW;r++){
				Log.d(TAG,"voy por la r= " + r);
				ySnap[r]=(int)(50+sizePieza/2 +r * sizePieza);
				if (c>0 || r>0){
					new PiezaMovible(c+ROW*r, xSnap[c], ySnap[r] , sizePieza, sizePieza, true);
				}
			}
		}
		*/
		//Log.d(TAG,"cree las piezas");
		
		
		/*for (int i = 0; i <= 4; i++) {
			canvas.drawLine(i * width / 4, 0, i * width / 4, height, paint);
			canvas.drawLine(0, i * height / 4, width, i * height / 4, paint);

		}
		*/
		holder.unlockCanvasAndPost(canvas);
		
		this.setWillNotDraw(false);
		
		
		
		/*pieza1 = new Pieza(0);
		Pieza pared = new Pieza(true, 200, 200);
		Pieza pieza2 = new Pieza(1, 400, 250);
		Pieza pieza3 = new Pieza(2, 800, 140);
		
		pieza1.piezaLeft=pared;
*/
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {

	}
	/*
	class Piezas extends ArrayList<Pieza>{
		public boolean pushRight(int id, float dx){
			boolean move=true;
			for (int i = 0; i< this.size() ; i++){
				if (i != id){
					if (get(id).checkColisionRight(get(i))) {
						if (get(i).isPared()){
							move = false;
						}else {
							move &= get
						}
					}
					
				}
			}
		}
	}
*/
}
